import React, { useState, useEffect } from 'react';
import { MessageList, MessageInput } from '../components/Chat';
import { Button, Avatar } from '../components/UI';
import { useChat, useFileUpload } from '../hooks';
// import { useWebSocket } from '../hooks/useWebSocketHook';
import { generateUUID, generateUserColor, getWebSocketUrl } from '../utils';

interface ChatPageProps {
  username: string;
  onLogout: () => void;
}

export const ChatPage: React.FC<ChatPageProps> = ({ username, onLogout }) => {
  const { user, messages, connectionStatus, sendTextMessage, setUser, connect, disconnect, deleteMessage } = useChat();
  const { uploadFile } = useFileUpload();
  const [isConnecting, setIsConnecting] = useState(false);
  const [isDragOver, setIsDragOver] = useState(false);
  const [dragCounter, setDragCounter] = useState(0);
  
  // 初始化用户
  useEffect(() => {
    if (!user && username) {
      const userId = generateUUID();
      setUser({
          username: username,
          userId: userId,
          randomColor: generateUserColor(userId), // 使用基于用户ID的确定性颜色
        });
    }
  }, [user, username, setUser]);
  
  // 连接状态管理
  useEffect(() => {
    if (user && connectionStatus === 'disconnected') {
      console.log('Attempting to connect to WebSocket...');
      // 使用工具函数获取WebSocket地址
      const wsUrl = getWebSocketUrl();
      connect(wsUrl);
    }
  }, [user, connectionStatus, connect]);

  
  // 监听连接状态变化，更新isConnecting状态
  useEffect(() => {
    if (connectionStatus === 'connecting') {
      setIsConnecting(true);
    } else {
      setIsConnecting(false);
    }
  }, [connectionStatus]);
  
  const handleSendMessage = (content: string) => {
    if (user && connectionStatus === 'connected') {
      sendTextMessage(content);
    }
  };
  
  const handleReconnect = () => {
    // 使用工具函数重连WebSocket
    const wsUrl = getWebSocketUrl();
    console.log('重连WebSocket地址:', wsUrl);
    connect(wsUrl);
  };
  
  // 拖拽事件处理
  const handleDragEnter = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragCounter(prev => prev + 1);
    if (e.dataTransfer.items && e.dataTransfer.items.length > 0) {
      setIsDragOver(true);
    }
  };
  
  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragCounter(prev => prev - 1);
    if (dragCounter <= 1) {
      setIsDragOver(false);
    }
  };
  
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  };
  
  const handleDrop = async (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(false);
    setDragCounter(0);
    
    const files = Array.from(e.dataTransfer.files);
    if (files.length > 0 && connectionStatus === 'connected') {
      try {
        for (const file of files) {
          await uploadFile(file);
        }
      } catch (error) {
        console.error('File upload failed:', error);
      }
    }
  };
  
  const getConnectionStatusText = () => {
    switch (connectionStatus) {
      case 'connecting':
        return '连接中...';
      case 'connected':
        return '已连接';
      case 'disconnected':
        return '已断开';
      case 'reconnecting':
        return '重连中...';
      default:
        return '未知状态';
    }
  };
  
  const getConnectionStatusColor = () => {
    switch (connectionStatus) {
      case 'connected':
        return 'text-green-600';
      case 'connecting':
      case 'reconnecting':
        return 'text-yellow-600';
      case 'disconnected':
        return 'text-red-600';
      default:
        return 'text-gray-600';
    }
  };
  
  const isDisabled = connectionStatus !== 'connected';
  
  return (
    <div 
      className="h-screen flex flex-col bg-gray-50 relative"
      onDragEnter={handleDragEnter}
      onDragLeave={handleDragLeave}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
    >
      {/* 头部 */}
      <header className="bg-white border-b px-4 py-3 flex items-center justify-between">
        <div className="flex items-center space-x-3">
          <div className="w-10 h-10 bg-blue-500 rounded-full flex items-center justify-center">
            <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
            </svg>
          </div>
          <div>
            <h1 className="text-lg font-semibold text-gray-900">聊天室</h1>
            <p className={`text-sm ${getConnectionStatusColor()}`}>
              {getConnectionStatusText()}
            </p>
          </div>
        </div>
        
        <div className="flex items-center space-x-3">
          {/* 用户信息 */}
          {user && (
            <div className="flex items-center space-x-2">
              <Avatar
                name={user.username}
                color={user.randomColor || '#9CA3AF'}
                size="sm"
              />
              <span className="text-sm font-medium text-gray-700">{user.username}</span>
            </div>
          )}
          
          {/* 重连按钮 */}
          {connectionStatus === 'disconnected' && (
            <Button
              variant="secondary"
              size="sm"
              onClick={handleReconnect}
              disabled={isConnecting}
              loading={isConnecting}
            >
              重连
            </Button>
          )}
          
          {/* 退出按钮 */}
          <Button
            variant="ghost"
            size="sm"
            onClick={() => {
              disconnect();
              onLogout();
            }}
          >
            退出
          </Button>
        </div>
      </header>
      
      {/* 消息列表 */}
      <MessageList
        messages={messages}
        currentUserId={user?.userId}
        className="flex-1"
        onDeleteMessage={deleteMessage}
      />
      
      {/* 连接状态提示 */}
      {connectionStatus === 'disconnected' && (
        <div className="bg-red-50 border-t border-red-200 px-4 py-2">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              <div className="w-2 h-2 bg-red-500 rounded-full"></div>
              <span className="text-sm text-red-700">连接已断开</span>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={handleReconnect}
              disabled={isConnecting}
              className="text-red-700 hover:bg-red-100"
            >
              点击重连
            </Button>
          </div>
        </div>
      )}
      
      {/* 输入区域 */}
      <MessageInput
        onSendMessage={handleSendMessage}
        disabled={isDisabled}
        placeholder={isDisabled ? '请等待连接...' : '请输入消息，可拖拽文件上传，可粘贴文件上传'}
      />
      
      {/* 拖拽覆盖层 */}
      {isDragOver && (
        <div className="absolute inset-0 bg-blue-500 bg-opacity-20 flex items-center justify-center z-50 pointer-events-none">
          <div className="bg-white rounded-lg shadow-lg p-8 border-2 border-dashed border-blue-500">
            <div className="text-center">
              <div className="w-16 h-16 mx-auto mb-4 bg-blue-100 rounded-full flex items-center justify-center">
                <svg className="w-8 h-8 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                </svg>
              </div>
              <h3 className="text-lg font-semibold text-gray-900 mb-2">拖拽文件到此处</h3>
              <p className="text-gray-600">支持图片、文档等多种文件格式</p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}